package cn.edu.swu.book;

import cn.edu.swu.core.BasicServlet;
import cn.edu.swu.core.JsonResponseWrapper;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.Objects;
import java.util.stream.Stream;

@WebServlet(urlPatterns = "/api/book/*")
public class BookApi extends BasicServlet {

    private BookService bookService = null;
    private ObjectMapper objectMapper = new ObjectMapper();
    private SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");

    public void init(ServletConfig config) {
        BookRepo repo = new BookRepo();
        bookService = new BookService();
        bookService.setRepo(repo);
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        this.methodRoute(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        this.methodRoute(request, response);
    }

    private void methodRoute(HttpServletRequest request, HttpServletResponse response) throws ServletException {
        String uri = request.getRequestURI();
        String method = uri.substring(uri.lastIndexOf("/") + 1);

        try {
            if (method.equals("list")) {
                this.list(request, response);
            } else if (method.equals("add")) {
                this.add(request, response);
            } else if (method.equals("search")) {
                this.handleAjaxSearch(request, response); // 处理搜索请求
            } else if (method.equals("searchByPriceRange")) {
                this.handleSearchByPriceRange(request, response); // 处理价格区间搜索请求
            }
        } catch (SQLException | IOException e) {
            throw new ServletException(e);
        }
    }

    public void list(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        try {
            List<Book> books = this.bookService.getAll();
            this.responseJson(response, true, books);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException{
        try {
            String json = this.getRequestBody(request);
            System.out.println(json);
            objectMapper.setDateFormat(dateFormatter);
            Book book = objectMapper.readValue(json, Book.class);
            this.bookService.save(book);
            this.responseJson(response, true, book);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleAjaxSearch(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        // 从请求体中获取JSON数据
        ObjectMapper mapper = new ObjectMapper();
        Map<String, Object> jsonMap = mapper.readValue(request.getReader().lines().collect(Collectors.joining(System.lineSeparator())), Map.class);

        // 获取第一个非空的搜索条件
        String key = Stream.of("name", "author", "publish", "price")
                .map(jsonMap::get)
                .filter(Objects::nonNull)
                .map(Object::toString)
                .findFirst()
                .orElseThrow(() -> new ServletException("搜索条件不能为空"));


        // 调用服务层进行搜索
        List<Book> books = this.bookService.search(key);

        // 响应头
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        this.responseJson(response, true, books);
    }

    // 价格区间搜索
    private void handleSearchByPriceRange(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ObjectMapper mapper = new ObjectMapper();
        try {
            Map<String, Object> jsonMap = mapper.readValue(request.getReader().lines().collect(Collectors.joining(System.lineSeparator())), Map.class);

            //System.out.println("JSON解析成功");
            //System.out.println("JSON Map: " + jsonMap);

            // 获取价格区间
            Double minPrice = Double.parseDouble(jsonMap.get("min").toString());
            Double maxPrice = Double.parseDouble(jsonMap.get("max").toString());
            //System.out.println("min，max的get和定义");
            //System.out.println("Min Price: " + minPrice + ", Max Price: " + maxPrice);
            if (minPrice == null || maxPrice == null) {
                System.out.println("两者为空");
                responseJson(response, false, "价格范围数据不完整");
                return;
            }

            List<Book> books = this.bookService.searchByPriceRange(minPrice, maxPrice);
            //System.out.println("BookApi开始调用BookServlet来定义");

            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");

            this.responseJson(response, true, books);

        } catch (JsonParseException | JsonMappingException e) {

            System.out.println("JSON解析异常: " + e.getMessage());
            e.printStackTrace();
            responseJson(response, false, "无法解析请求数据: " + e.getMessage());
        } catch (SQLException e) {

            System.out.println("SQL执行异常: " + e.getMessage());
            e.printStackTrace();
            responseJson(response, false, "数据库操作失败: " + e.getMessage());
        } catch (Exception e) {

            System.out.println("发生未知错误: " + e.getMessage());
            e.printStackTrace();
            responseJson(response, false, "服务器内部错误: " + e.getMessage());
        }
    }

}


